package com.lechi.web.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalCause;
import com.lechi.web.constants.AppCmdConstants;
import com.lechi.web.service.impl.IotDeviceCommond;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class ExpireCacheUtil {
//
//
//    @Bean
//    private Timer getTimer() {
//        Timer timer = new Timer();
//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//                cache.asMap().keySet().forEach(key -> {
//                    Optional<Date> ifPresent = Optional.ofNullable(cache.getIfPresent(key));
//                    if (ifPresent.filter(endTime -> new Date().getTime() - endTime.getTime() >= 60000L).isPresent()) {
//                        cache.invalidate(key);
//                    }
//                });
//            }
//        };
//        timer.schedule(timerTask, 60000L,60000L);
//        return timer;
//    }

    @Getter
   private final static Cache<String, Date> cache = CacheBuilder.newBuilder().removalListener(notification -> {
                if (RemovalCause.EXPLICIT == notification.getCause()) {
                    log.error("notification notification.getKey()：{}======{}==notification.getValue()数据:{}", notification.getKey(), notification.getValue(), notification.getCause());
                    CompletableFuture.runAsync(IotDeviceCommond.commond(notification.getKey(), AppCmdConstants.STOPED, notification.getValue()));
                }
            }).build();

    public static String ifTimeOut(String deviceIdOrSN, int timeInternal) {
        String state = Optional.ofNullable(cache.getIfPresent(deviceIdOrSN))
                .filter(endTime -> new Date().getTime() - endTime.getTime() <= timeInternal * 60000L)
                .map(endTime -> AppCmdConstants.STARTED).orElse(AppCmdConstants.STOPED);
        if (AppCmdConstants.STOPED.equals(state)) {
            cache.invalidate(deviceIdOrSN);
        }
        return state;
    }
}
